package com.masterclient.app.businessmodule.vipmodule.auth;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.eoner.baselibrary.utils.GlideEngineUtil;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.eoner.baselib.utils.activity.UtilActivity;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.eoner.baselibrary.utils.DoubleClickUtil;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.widget.loading.ProgressDialog;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.middlelib.router.map.FCRouterPath;
import com.masterclient.app.R;
import com.masterclient.app.base.CashTakePhotoDialog;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.settingmodule.auth.bean.OcrBean;
import com.masterclient.app.businessmodule.settingmodule.auth.widget.CashSubmitIDsDialog;
import com.masterclient.app.businessmodule.vipmodule.auth.contract.UploadIDsContract;
import com.masterclient.app.businessmodule.vipmodule.auth.contract.UploadIDsPresenter;
import com.megvii.demo.utils.Configuration;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(path = FCRouterPath.SETTING_AUTH_PATH)
public class UploadIDsActivity extends FCBusinessActivity<UploadIDsPresenter> implements UploadIDsContract.View, TextWatcher {

    @BindView(R.id.card_id)
    TextView card_id;
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.id_img0)
    ImageView id_img0;
    @BindView(R.id.id_img1)
    ImageView id_img1;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.view_img0_text)
    View view_img0_text;
    @BindView(R.id.view_img1_text)
    View view_img1_text;

    private ArrayList<Photo> selectedPhotoList = new ArrayList<>();
    public static final int IMAGE_PICKER = 102;
    public static final int REQUEST_CODE_SELECT = 100;

    RxPermissions rxPermissions;

    String amount = "";

    ProgressDialog progressDialog;

//    private int source = 0;
//    private int pageType = 0;

    private static final int INTO_IDCARDSCAN_PAGE = 100;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.upload_ids2;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("实名认证").setLineHidden(true);
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {

        StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#FFFFFF"));
        init();
        addListener();
    }

    private void init() {
//        source = getIntent().getIntExtra("source", 0);
//        pageType = getIntent().getIntExtra("pageType", 0);
        rxPermissions = new RxPermissions(this);
    }

    private void addListener() {

        InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                if (charSequence.equals(" "))
                    return "";
                return null;
            }
        };

        card_id.addTextChangedListener(this);
        name.addTextChangedListener(this);
        card_id.setFilters(new InputFilter[]{inputFilter});
        card_id.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                char[] aa = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
                return aa;
            }

            @Override
            protected char[] getReplacement() {
                char[] cc = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
                return cc;
            }
        });
    }

//    @Override
//    protected void onNavigationRightClick() {
//        super.onNavigationRightClick();
//        startActivitry(BridgeActivity.class, new String[][]{{"url", SystemConfigStorage.getInstance().getOcrExampleUrl()}, {"title", "查看示例"}});
//    }

    int img_flag = 0;//0 正面 1 反面

    @OnClick({R.id.next, R.id.id_img0_layout, R.id.id_img1_layout/*, R.id.contact_service*/})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.next:
                if (!TextUtils.isEmpty(name.getText().toString().trim())
                        && name.getText().toString().trim().length() > 0
                        && !TextUtils.isEmpty(card_id.getText().toString().trim())
                        && !TextUtils.isEmpty(img_url0)
                        && !TextUtils.isEmpty(img_url1)) {

                    if(TextUtils.isEmpty(img_url0)){
                        showToast("身份证正面照片不可为空");
                        return;
                    }
                    if(TextUtils.isEmpty(img_url1)){
                        showToast("身份证反面照片不可为空");
                        return;
                    }

                    if (TextUtils.isEmpty(name.getText().toString().trim())) {
                        showToast("姓名不可为空");
                        return;
                    }
                    if (TextUtils.isEmpty(card_id.getText().toString().trim())) {
                        showToast("身份证号码不可为空");
                        return;
                    }
                    if (!DoubleClickUtil.isClick(1000)) {
                        return;
                    }
                    show_submit_ids_dialog();
                }

                break;
            case R.id.id_img0_layout:
                img_flag = 0;
                Configuration.setCardType(this, 1);
                show_photo_dialog();
                break;
            case R.id.id_img1_layout:
                img_flag = 1;
                Configuration.setCardType(this, 2);
                show_photo_dialog();
                break;
//            case R.id.contact_service:
//                if (UserDataManager.getInstance().isSystemLogin()) {
//                    Information info = SobotManager.getBaseInfo();
//                    //SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.ShowFixedText,"实名认证服务");
//                    SobotApi.setChatTitleDisplayMode(mContext, SobotChatTitleDisplayMode.Default, "");
//                    SobotApi.startSobotChat(UploadIDsActivity.this, info);
//                } else {
//                    startActivity(new Intent(mContext, QuickLoginActivity.class));
//                }
//                break;
        }
    }

    CashSubmitIDsDialog submitIDsDialog;

    private void show_submit_ids_dialog() {
        if (submitIDsDialog == null) {
            submitIDsDialog = new CashSubmitIDsDialog(mContext);
        }
        submitIDsDialog.setOnChooseListerner(new CashSubmitIDsDialog.OnChooseListerner() {
            @Override
            public void cancel() {
                submitIDsDialog.dismiss();
            }

            @Override
            public void confirm() {
                submitIDsDialog.dismiss();
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(mContext);
                }
                progressDialog.show();
                mPresenter.ocr_info_send(name.getText().toString().trim(),card_id.getText().toString().trim());
            }
        });
        submitIDsDialog.show();
    }

    CashTakePhotoDialog photoDialog;

    private void show_photo_dialog() {
        if (photoDialog == null) {
            photoDialog = new CashTakePhotoDialog(mContext);
            photoDialog.setOnChooseListerner(new CashTakePhotoDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    photoDialog.dismiss();
                }

                @Override
                public void take_photo() {
                    photoDialog.dismiss();
                    rxPermissions
                            .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                EasyPhotos.createCamera(UploadIDsActivity.this)
                                        .setFileProviderAuthority("com.masterclient.app.fileprovider")
                                        .start(REQUEST_CODE_SELECT);
                            } else {
                                Toast.makeText(mContext, "文件权限或照相机权限申请失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                @Override
                public void select_photo() {
                    photoDialog.dismiss();
                    EasyPhotos.createAlbum(UploadIDsActivity.this, false, GlideEngineUtil.getInstance())
                            .start(REQUEST_CODE_SELECT);
                }
            });
        }
        photoDialog.show();
    }



    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        updateBottomBtnState();
    }

    public void updateBottomBtnState() {
        if (!TextUtils.isEmpty(name.getText().toString().trim())
                && name.getText().toString().trim().length() > 0
                && !TextUtils.isEmpty(card_id.getText().toString().trim())
                && !TextUtils.isEmpty(img_url0)
                && !TextUtils.isEmpty(img_url1)) {
            next.setBackgroundColor(Color.parseColor("#212121"));
        } else {
            next.setBackgroundColor(Color.parseColor("#CCCCCC"));
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    String img_url0, img_url1;

    @Override
    public void onUploadSuccess(UploadImgBean.DataBean dataBean) {
        if (img_flag == 0) {
            img_url0 = dataBean.getSh_image_url();
            GlideUtil.displayRoundImage(mContext, img_url0, id_img0, 1, R.mipmap.defaults_1);
        } else if (img_flag == 1) {
            img_url1 = dataBean.getSh_image_url();
            GlideUtil.displayRoundImage(mContext, img_url1, id_img1, 1, R.mipmap.defaults_1);
        }
    }

    @Override
    public void onIDOcrSuccess() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        UserDataManager.getInstance().updateUserIdCardRealName(name.getText().toString().trim());
        UserDataManager.getInstance().updateUserIdCardNumber(card_id.getText().toString().trim());
        showToast("成功");
        UtilActivity.finishStartNum(0,UtilActivity.getActivitySize()-1);
//        if (pageType == 1) {
//            //经销商实名
//            Intent intent = new Intent(UploadIDsActivity.this, SubmitIDsResultActivity.class);
//            intent.putExtra("pageType", 1);
//            startActivity(intent);
//            finish();
//        } else {
//            if (source == 0) {
//                finish();
//            } else {
//                Intent intent = new Intent(UploadIDsActivity.this, SubmitIDsResultActivity.class);
//                startActivity(intent);
//                finish();
//            }
//        }
    }

    @Override
    public void OnIDOcrFail(String code, String msg) {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        showToast(msg);
    }

    @Override
    public void OnNewOcrResult(OcrBean bean) {
        if (bean != null) {
            if (!TextUtils.isEmpty(bean.realName)) {
                name.setText(bean.realName);
            }
            if (!TextUtils.isEmpty(bean.identityCardNumber)) {
                card_id.setText(bean.identityCardNumber);
//                id_tip_layout.setVisibility(View.VISIBLE);
            }
            if (img_flag == 0) {
                //正面
                img_url0 = bean.frontImage;
            } else {
                if (!TextUtils.isEmpty(bean.backImage)) {
                    //背面
                    img_url1 = bean.backImage;
                }
            }
        }
        updateBottomBtnState();
    }

    @Override
    public void OnNewOcrResultFail(String msg) {
        if (img_flag == 0) {
            name.setText("");
            card_id.setText("");
            img_url0 = "";
        } else {
            img_url1 = "";
        }
        showToast(msg);
        updateBottomBtnState();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            //相机或相册回调
            if (requestCode == REQUEST_CODE_SELECT) {
                //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                ArrayList<Photo> resultPhotos =
                        data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);

                selectedPhotoList.clear();
                selectedPhotoList.addAll(resultPhotos);

                for (Photo item : selectedPhotoList) {
                    File file = new File(item.path);
                    Luban.with(this)
                            .load(file)
                            .setCompressListener(new OnCompressListener() { //设置回调
                                @Override
                                public void onStart() {
                                    // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                }

                                @Override
                                public void onSuccess(File file) {
                                    // TODO 压缩成功后调用，返回压缩后的图片文件
                                    Uri uri = Uri.fromFile(file);
                                    if (img_flag == 0) {
                                        id_img0.setImageURI(uri);
                                        view_img0_text.setVisibility(View.GONE);
                                        mPresenter.new_ocr(file, "1");
                                    } else {
                                        id_img1.setImageURI(uri);
                                        view_img1_text.setVisibility(View.GONE);
                                        mPresenter.new_ocr(file, "2");
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    // TODO 当压缩过程出现问题时调用
                                }
                            }).launch();    //启动压缩
                }
            }
            return;
        }
    }

}
